﻿using Ekton_Manage_DomainCore;
using Ekton_Manage_DomainCore.Aggregate;
using Ekton_Manage_DTO.RequestModels.User;
using Ekton_Manage_Framework.Methods;
using Ekton_Manage_InfrastructureCore.Common;
using Ekton_Manage_InfrastructureCore.Repositories;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Pomelo.AspNetCore.TimedJob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;

namespace Ekton_Manage_InfrastructureCore.common
{
    public class TimeJobUtils : Job
    {
        private readonly IBaseRepository<msg_push, int> _basemsgpushRepository;
        private readonly IBaseRepository<msg_user, int> _basemsguserRepository;
        private readonly IBaseRepository<user_msg, int> _baseusermsgRepository;
        private readonly IBaseRepository<msg_push, int> _baseMaterialRepository;
        private readonly ApplicationDbContent _content;
        private readonly IBaseRepository<user_list, int> _baseuserlistRepository;
        private readonly IBaseRepository<company_email, int> _basecompanyEmailrepository;
        private readonly ApplicationDbContent _Mddb;
        public TimeJobUtils(IBaseRepository<user_msg, int> baseusermsgRepository, IBaseRepository<company_email, int> basecompanyEmailrepository, IBaseRepository<user_list, int> baseuserlistRepository, ApplicationDbContent content, IBaseRepository<msg_push, int> baseMaterialRepository, IBaseRepository<msg_push, int> basemsgpushRepository, IBaseRepository<msg_user, int> basemsguserRepository, ApplicationDbContent Mddb)
        {
            _basemsgpushRepository = basemsgpushRepository;
            _basemsguserRepository = basemsguserRepository;
            _baseMaterialRepository = baseMaterialRepository;
            _baseuserlistRepository = baseuserlistRepository;
            _basecompanyEmailrepository = basecompanyEmailrepository;
            _baseusermsgRepository = baseusermsgRepository;
            _content = content;
            _Mddb = Mddb;
        }
        /// 定时查询消息推送状态，将state为1的并且时间点到了的消息 推送出去
        /// </summary>
        [Invoke(Begin = "2021-01-22 15:58", Interval = 1000 * 60, SkipWhileExecuting = false)]
        public async Task SelectMsgPush()
        {
            //系统定时发送
            var msgItem = await _basemsgpushRepository.QueryTableList(m => m.state == 0 && m.push == 0 && m.push_time.AddMinutes(1) >= DateTime.Now);
            if (msgItem is null)
            {
            }
            else
            {
                var updateMsgRes = await UpdateSingleDate(msgItem);
            }
            GC.Collect();

        }
        //[Invoke(Begin = "2021-01-22 15:58", Interval = 1000 * 20, SkipWhileExecuting = false)]
        public async Task SendEmail()
        {
            //最新的一条消息推送的id
            //var msg_id =_content.Set<msg_push>().Select(x => x.id).Max();
            var prouderType = await _baseMaterialRepository.QuerySingleData(m=>m.state == 0 && m.push == 1);
            if (prouderType == null) return;//如果为空，则表示没有消息需要推送
            DateTime startTime = prouderType.push_time;
            DateTime endTime = DateTime.Now;
            if (startTime.CompareTo(endTime) > 0)
            {
                //到了要推送的时间
                if (prouderType.push_user==0 && prouderType.push_method == 1)
                {
                    //全部用户
                    string address = "";//收件人
                    //查询全部用户
                    var userInfo = await _baseuserlistRepository.QueryTableList(m => true);
                    foreach (var item in userInfo)
                    {
                        address += item.email + ",";
                    }
                    //根据平台id查询公司邮箱
                    var companyEmail = await _basecompanyEmailrepository.QuerySingleData(m => m.platform_id == 26);
                    var username = companyEmail.email.Split("@")[0];//用户名
                    string password = companyEmail.author_code;//授权码
                    //邮箱推送消息
                    MailMessage mailMessage = new MailMessage();
                    //发件人
                    mailMessage.From = new MailAddress(companyEmail.email);

                    //邮件标题
                    mailMessage.Subject = prouderType.title;
                    //邮件内容
                    mailMessage.Body = prouderType.msg_context;
                    SmtpClient client = new SmtpClient();
                    client.Host = "smtp.qq.com";
                    client.EnableSsl = true;
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(username, password);
                    //将所有用户的邮箱遍历出来
                    string[] email = address.Split(',');
                    foreach (string name in email)
                    {
                        if (name is null) { };
                        if (name != string.Empty)
                        {
                            address = name;
                            mailMessage.To.Add(new MailAddress(address));
                            client.Send(mailMessage);
                        }
                    }
                    //发送之后，将这一条消息的state改为1
                    var res1 = await UpdateSingleEmail(prouderType.id);
                    Console.WriteLine("发送邮件成功");
                }
                else if (prouderType.push_user == 1)
                {
                    //指定用户
                }
            }
            else
            {
                Console.WriteLine("没有需要发送的邮件");
            }
            GC.Collect();
            
        }

        public async Task<int> UpdateSingleDate(List<msg_push> msgItems)
        {
            string claimInfo = string.Empty;
            var userInfo = JsonConvert.DeserializeObject<LoginUser>(claimInfo);
            foreach (var item in msgItems)
            {
                item.state = 1;
                item.edit_op_id = userInfo == null ? 0 : userInfo.id;
                item.edit_op_name = userInfo == null ? "" : userInfo.name;
                item.edit_op_date = DateTime.Now;
            }
            _Mddb.Set<msg_push>().UpdateRange(msgItems);
            await _Mddb.SaveChangesAsync();
            return 0;
        }

        public async Task<int> UpdateSingleEmail(int id)
        {
            string claimInfo = string.Empty;
            var userInfo = JsonConvert.DeserializeObject<LoginUser>(claimInfo);
            var msgItems = await _basemsgpushRepository.QueryTableList(m => m.id == id);
            foreach (var item in msgItems)
            {
                item.state = 1;
                item.edit_op_id = userInfo == null ? 0 : userInfo.id;
                item.edit_op_name = userInfo == null ? "" : userInfo.name;
                item.edit_op_date = DateTime.Now;
            }
            _Mddb.Set<msg_push>().UpdateRange(msgItems);
            await _Mddb.SaveChangesAsync();
            return 0;
        }

    }
}
